import numpy as np
import cv2
import matplotlib.pyplot as plt
import math


def main():
	img=cv2.imread('../images/airplane.png',0)

	# image_copy = img.copy()
	# for x in range(image_copy.shape[0]):
	# 	for y in range(image_copy.shape[1]):
	# 		image_copy[x, y] *= math.pow(-1,x+y)

	# 对图像进行二维fft变换
	f = np.fft.fft2(img)
	# 将低频成分搬移到图像中心
	fshift = np.fft.fftshift(f)

	fre_m = np.abs(fshift)   #幅度谱，求模得到
	fre_p = np.angle(fshift) 	 #相位谱，求相角得到
	#把幅度谱和相位谱再合并为复数形式的频域图数据(在处理幅度谱的时候有用)
	fre_ = fre_m * np.e**(1j*fre_p)

	# 显示幅度谱 log
	magnitude_spectrum = 20*np.log(np.abs(fshift)+1)
	# 相位谱
	phase_spectrum = np.angle(fshift)

	print(img.shape)
	rows, cols = img.shape
	crow,ccol = rows//2 , cols//2
	fre_m[crow-30:crow+30, ccol-30:ccol+30] = 0
	fre_ = fre_m * np.e**(1j*fre_p)
	f_ishift = np.fft.ifftshift(fre_)	
	img_back = np.fft.ifft2(f_ishift)
	img_back = np.abs(img_back)

	fshift[crow-30:crow+30, ccol-30:ccol+30] = 0
	f_ishift = np.fft.ifftshift(fshift)	
	img_back2 = np.fft.ifft2(f_ishift)
	img_back2 = np.abs(img_back2)



	plt.subplot(141),plt.imshow(img, cmap = 'gray')
	plt.title('Input Image'), plt.xticks([]), plt.yticks([])
	plt.subplot(142),plt.imshow(magnitude_spectrum, cmap = 'gray')
	plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])
	plt.subplot(143),plt.imshow(img_back, cmap = 'gray')
	plt.title('Image after HPF 1'), plt.xticks([]), plt.yticks([])
	plt.subplot(144),plt.imshow(img_back2, cmap = 'gray')
	plt.title('Image after HPF'), plt.xticks([]), plt.yticks([])
	plt.show()

if __name__ == '__main__':
	main()